using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using QFramework;
using UnityEngine;

namespace QGameFramework.Tools
{
    public partial class Tool
    {
        public void WriteBin2File<T>(T t, string filePath) where T : new()
        {
            BinaryFormatter bfw = new BinaryFormatter();
            FileStream fsw = File.Create(Application.streamingAssetsPath + filePath);
            bfw.Serialize(fsw, t);
            fsw.Close();
        }

        public void WriteBin2File<T>(string filePath, T t) where T : new()
        {
            BinaryFormatter bfw = new BinaryFormatter();
            FileStream fsw = File.Create(Application.streamingAssetsPath + filePath);
            bfw.Serialize(fsw, t);
            fsw.Close();
        }

        public bool ReadBin2File<T>(string filePath, out T t) where T : new()
        {
            if (File.Exists(Application.streamingAssetsPath + filePath))
            {
                LogKit.E("找到文件了");
                BinaryFormatter bfr = new BinaryFormatter();
                FileStream fsr = File.Open(Application.streamingAssetsPath + filePath, FileMode.Open);
                t = (T)bfr.Deserialize(fsr);
                fsr.Close();
                return true;
            }
            else
            {
                LogKit.E("没找到文件");
                t = new T();
                return false;
            }
        }

        public bool ReadBin2File<T>(out T t, string filePath) where T : new()
        {
            if (File.Exists(Application.streamingAssetsPath + filePath))
            {
                BinaryFormatter bfr = new BinaryFormatter();
                FileStream fsr = File.Open(Application.streamingAssetsPath + filePath, FileMode.Open);
                t = (T)bfr.Deserialize(fsr);
                fsr.Close();
                return true;
            }
            else
            {
                t = new T();
                return false;
            }
        }
    }
}